package com.net.oil.main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import com.baidu.mobstat.StatService;
import com.net.oil.BuildConfig;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseActivity;
import com.net.oil.base.EventBussMessage;
import com.net.oil.gaode.LocationHandle;
import com.net.oil.main.bean.AppVersionInfo;
import com.net.oil.main.bean.InitCoupon;
import com.net.oil.main.bean.NewAccountCoupon;
import com.net.oil.main.contract.MainContract;
import com.net.oil.main.fragment.FragmentFactory;
import com.net.oil.main.fragment.NewAccountCouponDialogFragment;
import com.net.oil.main.presenter.MainPresenter;
import com.net.oil.permission.RuntimeRationale;
import com.net.oil.update.UpdateActivity;
import com.net.oil.util.AppInfo;
import com.net.oil.util.StringUtil;
import com.tencent.bugly.Bugly;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Setting;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {

    @BindView(R.id.bottom_bar_layout)
    RadioGroup bottomBarLayout;
    @BindView(R.id.fragment_layout)
    FrameLayout fragmentLayout;

    private Map<Integer, Fragment> fragmentMap;
    private Fragment currentFragment;       //当前的fragment
    private FragmentManager fragmentManager;    //fragment manager
    private FragmentTransaction fragmentTransaction;        //fragment transaction
    private LocationHandle locationHandle;          //定位类

    private int appLocalVersionCode;         //本地app versionName

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        stat();
        locationHandle = LocationHandle.getInstance();  //获取定位类的实例
        locationHandle.initLocation(getApplicationContext());
        presenter = new MainPresenter(this);
        presenter.attachView(this);
        requestPermission(Permission.Group.LOCATION);
        initView();
        initData();
    }

    private void initData() {
        /* 获取服务器端版本号 */
        presenter.getVersion();
        /* 获取用户是否有未领取的优惠券 */
        presenter.initCoupon();
        /* 上传极光推送id */
        if (UserInfoManager.getInstance().isLogin()) {
            postJPushId();
        }
        /* bugly检查更新初始化 */
        Bugly.init(getApplicationContext(), "bd132df142", BuildConfig.DEBUG);
    }

    /**
     * 上传极光id
     */
    private void postJPushId() {
        String id = JPushInterface.getRegistrationID(this.getApplicationContext());
        if (!StringUtil.isEmpty(id)) {
            presenter.postJPushId(id, 1);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationHandle != null) {
            locationHandle.stopLocation();
            locationHandle.destroyLocation();
        }
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        fragmentManager = getSupportFragmentManager();
        initFirstFragment();

        bottomBarLayout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
                Fragment fragmentCheck = fragmentMap.get(checkId);
                if (fragmentCheck == null) {
                    fragmentCheck = FragmentFactory.getInstance(checkId);
                    fragmentMap.put(checkId, fragmentCheck);
                }
                switchView(currentFragment, fragmentCheck);
                currentFragment = fragmentCheck;
            }
        });

    }

    //初始化第一个fragment
    private void initFirstFragment() {
        fragmentMap = new HashMap<>();
        currentFragment = FragmentFactory.getInstance(R.id.home_page_button);
        fragmentMap.put(R.id.home_page_button, currentFragment);
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_layout, currentFragment);
        fragmentTransaction.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * fragment切换
     *
     * @param fragment      当前显示的fragment
     * @param fragmentCheck 选中将要显示的fragment
     */
    private void switchView(Fragment fragment, Fragment fragmentCheck) {
        fragmentTransaction = fragmentManager.beginTransaction();
        if (fragmentCheck.isAdded()) {
            fragmentTransaction.hide(fragment).show(fragmentCheck).commit();
        } else {
            fragmentTransaction.hide(fragment).add(R.id.fragment_layout, fragmentCheck).commit();
        }
    }

    /**
     * 百度统计
     */
    private void stat() {
        // 如果没有页面和事件埋点，此代码必须设置，否则无法完成接入
        // 设置发送策略，建议使用 APP_START
        // 发送策略，取值 取值 APP_START、SET_TIME_INTERVAL、ONCE_A_DAY
        // 备注，SET_TIME_INTERVAL与ONCE_A_DAY，如果APP退出或者进程死亡，则不会定时发送
        // 建议此代码不要在Application中设置，否则可能因为进程重启等造成启动次数高，具体见web端sdk帮助中心
        // StatService.setSendLogStrategy(this, SendStrategyEnum.APP_START, 1, false);

        // setSendLogStrategy已经@deprecated，建议使用新的start接口
        // 如果没有页面和自定义事件统计埋点，此代码一定要设置，否则无法完成统计
        // 进程第一次执行此代码，会导致发送上次缓存的统计数据；若无上次缓存数据，则发送空启动日志
        // 由于多进程等可能造成Application多次执行，建议此代码不要埋点在Application中，否则可能造成启动次数偏高
        // 建议此代码埋点在统计路径触发的第一个页面中，若可能存在多个则建议都埋点
        StatService.start(this);
    }

    /**
     * 上传极光推送id成功
     */
    @Override
    public void postJPushIdSuccess() {

    }

    /**
     * 上传极光推送id失败
     */
    @Override
    public void postJPushIdFailed() {

    }

    /**
     * 获取新用户注册赠送优惠券成功
     *
     * @param newAccountCoupons 优惠券列表
     */
    @Override
    public void searchNewAccountCouponSuccess(List<NewAccountCoupon> newAccountCoupons) {
        if (newAccountCoupons != null && newAccountCoupons.size() > 0) {
            showCouponDialog(newAccountCoupons);
        }
    }

    /**
     * 获取新用户注册赠送优惠券失败
     */
    @Override
    public void searchNewAccountCouponFailed() {

    }

    /**
     * 获取用户是否有未领取的优惠券成功
     *
     * @param initCoupon 返回结果
     */
    @Override
    public void initCouponSuccess(InitCoupon initCoupon) {
        /* isHasCoupon 为true，有未领取的优惠券，则获取优惠券 */
        if (initCoupon.isHasCoupon()) {
            presenter.searchNewAccountCoupon();      //获取优惠券
        }
    }

    /**
     * 获取用户是否有未领取的优惠券失败
     */
    @Override
    public void initCouponFailed() {

    }

    /**
     * 获取服务器端版本成功
     *
     * @param appVersionInfo 服务端版本信息
     */
    @Override
    public void getVersionSuccess(AppVersionInfo appVersionInfo) {
        appLocalVersionCode = AppInfo.getVersionCode();
        if (appLocalVersionCode != -1 && appVersionInfo.getCode() > appLocalVersionCode) {
            String updateMessage = appVersionInfo.getVersionInfo();
            showUpdateDialog(updateMessage, appVersionInfo);
        }
    }

    /**
     * 获取服务器端版本失败
     */
    @Override
    public void getVersionFailed() {

    }

    /**
     * 更新提示
     *
     * @param message    提示信息
     * @param appVersionInfo    更新版本信息
     */
    private void showUpdateDialog(String message, final AppVersionInfo appVersionInfo) {

        final boolean isForuce = appVersionInfo.isForceUpdate();       //是否是强制更新
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(MainActivity.this, UpdateActivity.class);
                intent.putExtra(UpdateActivity.APP_INFO, appVersionInfo);
                startActivity(intent);
                finish();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isForuce) {
                    finish();
                } else {
                    dialog.dismiss();
                }
            }
        });
        builder.setCancelable(!isForuce);
        builder.show();

    }

    /**
     * 显示优惠券弹出框
     *
     * @param newAccountCoupons 优惠券数据
     */
    private void showCouponDialog(List<NewAccountCoupon> newAccountCoupons) {
        NewAccountCouponDialogFragment fragment = NewAccountCouponDialogFragment.newInstance(newAccountCoupons);
        fragment.show(getSupportFragmentManager(), "dialog");
    }

    /**
     * 接受有优惠券未领取消息
     *
     * @param message 消息
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void receiveEventBus(EventBussMessage message) {
        if (message.getCode() == Constant.HAS_COUPON_CODE) {
            presenter.searchNewAccountCoupon();     //获取优惠券
        }
    }

    private void exit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setTitle("提示");
        builder.setMessage("您要退出吗？");
        builder.show();
    }

    /**
     * 请求权限.
     */
    private void requestPermission(String... permissions) {
        String per = getString(R.string.location_permission_tip);
        AndPermission.with(this)
                .runtime()
                .permission(permissions)
                .rationale(new RuntimeRationale(per))
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        /* 请求权限成功 */
                        if (locationHandle != null) {
                            locationHandle.startLocation();
                        }
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        /*  请求权限失败 */
                        if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions)) {
                            /* 请求权限失败，需要去设置里面重新设置 */
                            showSettingDialog(MainActivity.this, permissions);
                        } else {
                            finish();
                        }
                    }
                })
                .start();
    }

    /**
     * 显示设置弹框.
     */
    public void showSettingDialog(Context context, final List<String> permissions) {
        List<String> permissionNames = Permission.transformText(context, permissions);
        String message = getString(R.string.location_permission_tip);

        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle(R.string.permission_dialog_title)
                .setMessage(message)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPermission();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .show();
    }

    /**
     * 从设置回来，再次去检验权限
     */
    private void setPermission() {
        AndPermission.with(this)
                .runtime()
                .setting()
                .onComeback(new Setting.Action() {
                    @Override
                    public void onAction() {
                        requestPermission(Permission.Group.LOCATION);
                    }
                })
                .start();
    }

}
